import PictureCard from '@/components/PictureCard';
import PictureSearchForm from '@/components/PictureSearchForm';
import UpdatePictureModal from '@/components/UpdatePictureModal';
import usePictureTagCategory from '@/hooks/usePictureTagCategory';
import CreatePictureModal from '@/pages/My/components/CreatePictureModal';
import AddUserToSpaceModal from '@/pages/My/Team/components/AddUserToSpaceModal';
import CreateModal from '@/pages/My/Team/components/CreateModal';
import MyJoinTeamModal from '@/pages/My/Team/components/MyJoinTeamModal';
import {deletePictureUsingPost, listPictureVoByPageUsingPost,} from '@/services/backend/pictureController';
import {getMyTeamSpaceUsingPost, getSpaceVoByIdUsingGet} from '@/services/backend/spaceController';
import {DotChartOutlined, PlusOutlined, UsergroupAddOutlined} from '@ant-design/icons';
import {PageContainer, ProColumns} from '@ant-design/pro-components';
import '@umijs/max';
import {useNavigate} from '@umijs/max';
import {Button, Image, List, message, Select, Space, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {useParams} from "react-router";

/**
 * 用户管理页面
 *
 * @constructor
 */
const columns: ProColumns<API.SpaceVO>[] = [
  {
    title: '空间名称',
    dataIndex: 'spaceName',
    valueType: 'text',
  },
  {
    title: '空间类型',
    dataIndex: 'spaceType',
    valueType: 'text',
    hideInForm: true,
  },
];
const DEFAULT_PAGE_PARAMS: PageRequest = {
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
};

const IndexPage: React.FC = () => {
  const {spaceId} = useParams();
  const [space, setSpace] = useState<API.SpaceVO>();
  const [loading, setLoading] = useState<boolean>(true);
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [createPictureModalVisible, setCreatePictureModalVisible] = useState<boolean>(false);
  const [updatePictureModalVisible, setUpdatePictureModalVisible] = useState<boolean>(false);
  const [addUserToSpaceModalVisible, setAddUserToSpaceModalVisible] = useState<boolean>(false);
  const [myJoinTeamModalVisible, setMyJoinTeamModalVisibleModalVisible] = useState<boolean>(false);
  const [currentData, setCurrentData] = useState<API.PictureVO>();
  const [formLoading, setFormLoading] = React.useState<boolean>(true);
  const [dataList, setDataList] = React.useState<API.PictureVO[]>([]);
  const [total, setTotal] = React.useState<number>(0);
  const listRef = useRef(null);
  const navigate = useNavigate();
  const [searchParam, setSearchParam] = React.useState<API.PictureQueryRequest>({
    ...DEFAULT_PAGE_PARAMS,
  });

  const {tagList, categoryList} = usePictureTagCategory();
  /**
   * 表格列配置
   */
  const pictureColumns: ProColumns<API.PictureVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '图片',
      hideInSearch: true,
      dataIndex: 'url',
      valueType: 'image',
      renderFormItem(_, record) {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'column', // 垂直排列
              justifyContent: 'center', // 垂直居中
              alignItems: 'center', // 水平居中
              gap: 10,
            }}
          >
            <Image src={record.value} alt={record.value} width={100} height={100}/>
          </div>
        );
      },
    },
    {
      title: '图片名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '分类',
      dataIndex: 'category',
      valueType: 'text',
      renderFormItem(schema) {
        const {fieldProps} = schema;

        //@ts-ignore
        return (
          <Select
            options={categoryList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
          />
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      renderFormItem(schema) {
        const {fieldProps} = schema;
        //@ts-ignore
        return (
          <Select
            options={tagList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
            mode="tags"
          />
        );
      },
      render(_, record) {
        if (!record.tags) {
          return <></>;
        }
        return record.tags.map((tag) => {
          return (
            <Tag style={{marginBottom: 10}} key={tag}>
              {tag}
            </Tag>
          );
        });
      },
    },
    {
      title: '简介',
      dataIndex: 'introduction',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];
  const doSearch = async () => {
    if (!loading) {
      setFormLoading(true);
      try {
        const res = await listPictureVoByPageUsingPost(searchParam);
        setDataList(res.data?.records ?? []);
        setTotal(res.data?.total ?? 0);
      } catch (e: any) {
        message.error('获取数据失败：' + e.message);
      }
      setFormLoading(false);
    }
  };
  useEffect(() => {
    doSearch();
  }, [searchParam]);

  async function getMyTeamSpace() {
    setLoading(true);
    let res;
    if (!spaceId) {
      res = await getMyTeamSpaceUsingPost();
    } else {
      res = await getSpaceVoByIdUsingGet({
        id: spaceId,
      });
    }
    const fetchSpace = res?.data;
    setSpace(fetchSpace);
    setSearchParam({
      ...searchParam,
      spaceId: fetchSpace?.id,
    });
    setLoading(false);
  }

  useEffect(() => {
    if (!loading) {
      if (space) {
        setCreateModalVisible(false);
      } else {
        setCreateModalVisible(true);
      }
    }
  }, [loading]);

  useEffect(() => {
    getMyTeamSpace();
  }, [spaceId]);
  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.PictureVO) => {
    const hide = message.loading('正在删除');
    const ids: string[] = [row.id as any];

    const batchDeleteRequest: API.BatchDeleteRequest = {
      ids,
    };
    if (!row) return true;
    try {
      await deletePictureUsingPost(batchDeleteRequest);
      hide();
      message.success('删除成功');
      setSearchParam({
        ...searchParam,
      });
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };
  const onEdit = (data: API.PictureVO) => {
    setCurrentData(data);
    setUpdatePictureModalVisible(true);
  };
  return (
    <div>
      {!loading && (
        <PageContainer
          title={space?.spaceName}
          tabBarExtraContent={
            <Space>
              <Button
                onClick={() => {
                  navigate(`/analyze/${space?.id}`);
                }}
                style={{marginBottom: 20}}
              >
                <DotChartOutlined/> 空间分析
              </Button>

              <Button
                onClick={() => {
                  setMyJoinTeamModalVisibleModalVisible(true)
                }}
                style={{marginBottom: 20}}
              >
                <UsergroupAddOutlined/> 我加入的团队
              </Button>
              {!spaceId && <Button
                onClick={() => {
                  setAddUserToSpaceModalVisible(true);
                }}
                style={{marginBottom: 20}}
              >
                <UsergroupAddOutlined/> 添加人员
              </Button>
              }
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  setCreatePictureModalVisible(true);
                }}
                style={{marginBottom: 20}}
              >
                <PlusOutlined/> 上传图片
              </Button>
            </Space>
          }
        >
          <PictureSearchForm
            onSearch={(values) => {
              console.log(values);
              //@ts-ignore
              const editTimeRange = values?.editTimeRange;
              setSearchParam({
                ...searchParam,
                ...values,
                startEditTime: editTimeRange?.[0].toDate(),
                endEditTime: editTimeRange?.[1].toDate(),
                spaceId: space?.id,
              });
            }}
          />
          <List<API.PictureVO>
            style={{
              marginTop: 24,
            }}
            ref={listRef}
            rowKey="id"
            grid={{
              gutter: 16,
              xs: 1,
              sm: 2,
              md: 3,
              lg: 3,
              xl: 4,
              xxl: 4,
            }}
            pagination={{
              current: searchParam.current,
              pageSize: searchParam.pageSize,
              total: total,
              onChange: (current, pageSize) => {
                setSearchParam({
                  ...searchParam,
                  current: current,
                  pageSize: pageSize,
                  spaceId: space?.id,
                });
              },
            }}
            loading={formLoading}
            dataSource={dataList}
            renderItem={(data) => (
              <List.Item key={data.id} style={{}}>
                <PictureCard
                  canEdit={true}
                  canDelete={true}
                  data={data}
                  onDelete={() => handleDelete(data)}
                  onEdit={() => {
                    onEdit(data);
                  }}
                />
              </List.Item>
            )}
          ></List>

          <CreatePictureModal
            spaceId={space?.id}
            visible={createPictureModalVisible}
            onSubmit={() => {
              setCreatePictureModalVisible(false);
              setSearchParam({
                ...searchParam,
              });
            }}
            onCancel={() => {
              setCreatePictureModalVisible(false);
            }}
          />
          <CreateModal
            columns={columns}
            visible={createModalVisible}
            onSubmit={async () => {
              await getMyTeamSpace();
              setCreateModalVisible(false);
            }}
          />
          <UpdatePictureModal
            oldData={currentData}
            visible={updatePictureModalVisible}
            columns={pictureColumns}
            onSubmit={() => {
              setSearchParam({
                ...searchParam,
              });
              setUpdatePictureModalVisible(false);
            }}
            onCancel={() => {
              setUpdatePictureModalVisible(false);
            }}
          />
          {!spaceId&&<AddUserToSpaceModal
            visible={addUserToSpaceModalVisible}
            spaceId={space?.id}
            onSubmit={() => {
              setAddUserToSpaceModalVisible(false);
            }}
            onCancel={() => {
              setAddUserToSpaceModalVisible(false);
            }}
          />}
          <MyJoinTeamModal
            visible={myJoinTeamModalVisible}
            onSubmit={() => {
              setMyJoinTeamModalVisibleModalVisible(false);
            }}
            onCancel={() => {
              setMyJoinTeamModalVisibleModalVisible(false);
            }}
          />
        </PageContainer>
      )}
    </div>
  );
};

export default IndexPage;
